﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Kinect;
using Microsoft.Expression.Encoder.Devices;
using WebcamControl;
using System.IO;
using System.Drawing.Imaging;
using Microsoft.Speech.AudioFormat;
using Microsoft.Speech.Recognition;

namespace PhysioAssist2Win
{
    /// <summary>
    /// Interaction logic for FotosVideos.xaml
    /// </summary>
    public partial class FotosVideos : Window
    {





        //VARIAVEIS KINECT
        private KinectSensor sensor;
        private WriteableBitmap colorBitmap;
        //private SpeechRecognitionEngine speechEngine;
        private byte[] colorPixels;
        Skeleton[] sklts = new Skeleton[6];

        //VIDEO



        //KINECT
        private void winFotosVideos_Loaded(object sender, RoutedEventArgs e)
        {
            //Obtem o sensor ativo
            foreach (var potentialSensor in KinectSensor.KinectSensors)
            {
                if (potentialSensor.Status == KinectStatus.Connected)
                {
                    sensor = potentialSensor;
                    break;
                }
            }


            if (null != sensor)
            {

                //Habilita imagem e esqueletos
                sensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30);
                sensor.SkeletonStream.Enable();

                //Preparação da imagem do Kinect
                colorPixels = new byte[sensor.ColorStream.FramePixelDataLength];
                colorBitmap = new WriteableBitmap(sensor.ColorStream.FrameWidth, sensor.ColorStream.FrameHeight, 96.0, 96.0, PixelFormats.Bgr32, null);
                //colorBitmap = new WriteableBitmap(int.Parse(imgKinect.Width.ToString()), int.Parse(imgKinect.Height.ToString()), 96.0, 96.0, PixelFormats.Bgr32, null);
                imgKinect.Source = colorBitmap;

                //Eventos de Frame Ready
                sensor.ColorFrameReady += sensor_ColorFrameReady;
                sensor.SkeletonFrameReady += sensor_SkeletonFrameReady;

                try
                {
                    sensor.Start();
                }
                catch (System.IO.IOException)
                {
                    sensor = null;
                }
            }








            ////RECONHECIMENTO DE VOZ
            //RecognizerInfo ri = GetKinectRecognizer();

            //if (null != ri)
            //{

            //    this.speechEngine = new SpeechRecognitionEngine(ri.Id);

            //    // Create a grammar from grammar definition XML file.
            //    using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(Properties.Resources.PhysioAssistGrammar)))
            //    {
            //        var g = new Grammar(memoryStream);
            //        speechEngine.LoadGrammar(g);
            //    }

            //    speechEngine.SpeechRecognized += SpeechRecognized;

            //    speechEngine.SetInputToAudioStream(sensor.AudioSource.Start(), new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
            //    speechEngine.RecognizeAsync(RecognizeMode.Multiple);
            //}
            //else
            //{
            //    lblNome.Content = "Erro";
            //}










        }
        private void winFotosVideos_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //Ao fechar a janela, salvar os dados armazenados no banco
            //SalvaLog();


            //E desocupar o Kinect
            if (null != this.sensor)
            {
                this.sensor.Stop();
            }
        }
        void sensor_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {


            SkeletonFrame sf = e.OpenSkeletonFrame();

            if (sf != null)
            {

                //Cria array de esqueletos e recebe o skeletonframe
                sf.CopySkeletonDataTo(sklts);


                //Cria esqueleto
                Skeleton sklt = new Skeleton();


                //Pega primeiro esqueleto traqueado
                foreach (Skeleton sk in sklts)
                {
                    if (sk.TrackingState == SkeletonTrackingState.Tracked)
                    {
                        sklt = sk;
                        break;
                    }
                }





                //Só entra aqui se existir um esqueleto traqueado
                if (sklt.TrackingState == SkeletonTrackingState.Tracked)
                {






                }



            }

        }
        void sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {
                if (colorFrame != null)
                {
                    colorFrame.CopyPixelDataTo(this.colorPixels);

                    this.colorBitmap.WritePixels(
                        new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                        this.colorPixels,
                        this.colorBitmap.PixelWidth * sizeof(int),
                        0);
                }
            }
        }








        //JANELA
        public FotosVideos()
        {
            InitializeComponent();


            //Ajusta posição e tamanho das janelas
            double width = System.Windows.SystemParameters.PrimaryScreenWidth;
            double height = System.Windows.SystemParameters.PrimaryScreenHeight;

            winFotosVideos.Width = width;
            winFotosVideos.Height = height;

            winFotosVideos.Left = 0;
            winFotosVideos.Top = 0;



            //Larguras dos Paineis
            pnlEsq.Width = winFotosVideos.Width * 0.2;
            pnlEsq.Height = winFotosVideos.Height;
            pnlEsq.Margin = new Thickness(20, 20, 0, 0);

            pnlDir.Width = (winFotosVideos.Width - 60) * 0.8;
            pnlDir.Height = winFotosVideos.Height;
            pnlDir.Margin = new Thickness(20, 20, 0, 0);


            //Imagem Kinect
            imgKinect.Width = pnlDir.Width;
            imgKinect.Height = pnlDir.Height - 150;
            imgKinect.Margin = new Thickness(-220, 0, 0, 0);









        }








        //VOLTAR
        private void pnlEsq_MouseDown(object sender, MouseButtonEventArgs e)
        {
            winFotosVideos.Close();
        }









        //GRAVAR E PARAR
        //private void imgGravar_MouseDown(object sender, MouseButtonEventArgs e)
        //{
        //    imgParar.Visibility = System.Windows.Visibility.Visible;
        //    imgGravar.Visibility = System.Windows.Visibility.Hidden;

        //    //cap.Start();

        //}
        //private void imgParar_MouseDown(object sender, MouseButtonEventArgs e)
        //{

        //    imgParar.Visibility = System.Windows.Visibility.Hidden;
        //    imgGravar.Visibility = System.Windows.Visibility.Visible;
        //}






        //FOTO
        private void imgFoto_MouseDown(object sender, MouseButtonEventArgs e)
        {

            //CreateThumbnail(System.DateTime.Now.ToString() + ".bmp", colorBitmap.Clone());
            string filename = Properties.Resources.Path + DateTime.Now.ToString().Trim().Replace(":", "").Replace("/", "") + ".png";
            CreateThumbnail(filename, colorBitmap.Clone());



        }
        void CreateThumbnail(string filename, BitmapSource image5)
        {
            if (filename != string.Empty)
            {
                using (FileStream stream5 = new FileStream(filename, FileMode.Create))
                {
                    PngBitmapEncoder encoder5 = new PngBitmapEncoder();
                    encoder5.Frames.Add(BitmapFrame.Create(image5));
                    encoder5.Save(stream5);
                    stream5.Close();
                }
            }
        }









        //RECONHECIMENTO DE VOZ
        private static RecognizerInfo GetKinectRecognizer()
        {
            foreach (RecognizerInfo recognizer in SpeechRecognitionEngine.InstalledRecognizers())
            {
                string value;
                recognizer.AdditionalInfo.TryGetValue("Kinect", out value);
                if ("True".Equals(value, StringComparison.OrdinalIgnoreCase) && "en-US".Equals(recognizer.Culture.Name, StringComparison.OrdinalIgnoreCase))
                {
                    return recognizer;
                }
            }

            return null;
        }
        private void SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            // Speech utterance confidence below which we treat speech as if it hadn't been heard
            const double ConfidenceThreshold = 0.3;

            if (e.Result.Confidence >= ConfidenceThreshold)
            {
                switch (e.Result.Semantics.Value.ToString())
                {
                    case "BAATE":
                        imgFoto_MouseDown(null, null);
                        break;

                    case "TEERA":
                        imgFoto_MouseDown(null, null);
                        break;


                }
            }
        }





    }
}
